package com.leetcode.algorithm.y22.m07.w4;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 15. 三数之和
 * 
 * https://leetcode.cn/problems/3sum/
 * 
 * @author jie.deng
 *
 */
class Question0015Solution01 {

	public List<List<Integer>> threeSum(int[] nums) {
		List<List<Integer>> result = new ArrayList<>();
		int len = nums.length;
		if (len < 3) {
			return result;
		}
		Arrays.sort(nums);

		int sum = 0;
		for (int idx1 = 0; idx1 < len - 2; idx1++) {
			if (nums[idx1] + nums[idx1 + 1] + nums[idx1 + 2] > 0) {
				break;
			}
			if (idx1 > 0 && nums[idx1] == nums[idx1 - 1]) {
				continue;
			}
			sum += nums[idx1];
			for (int idx2 = idx1 + 1; idx2 < len - 1; idx2++) {
				if (nums[idx1] + nums[idx2] + nums[idx2 + 1] > 0) {
					break;
				}
				if (idx2 > idx1 + 1 && nums[idx2] == nums[idx2 - 1]) {
					continue;
				}
				sum += nums[idx2];
				int idx3 = searchIdx(nums, -sum, idx2 + 1);
				if (idx3 != -1) {
					result.add(Arrays.asList(nums[idx1], nums[idx2], nums[idx3]));
				}
				sum -= nums[idx2];
			}
			sum -= nums[idx1];
		}

		return result;
	}

	private int searchIdx(int[] nums, int target, int left) {
		int right = nums.length - 1;
		while (left <= right) {
			int mid = left + ((right - left) >> 1);
			if (nums[mid] == target) {
				return mid;
			} else if (nums[mid] > target) {
				right = mid - 1;
			} else {
				left = mid + 1;
			}
		}
		return -1;
	}

}